package auto

import (
	"go-stock/backend/data"
	"go-stock/backend/db"
	"go-stock/backend/logger"
	"go-stock/backend/models"
	"go-stock/backend/util"
	"log"
)

// AutoMigrate 自动迁移数据库
func AutoMigrate() {

	models := util.RegisteredModels
	//models := []interface{}{
	//	&data.StockInfo{},
	//	&data.StockBasic{},
	//	&data.FollowedStock{},
	//	&data.IndexBasic{},
	//	&data.Settings{},
	//	&models.AIResponseResult{},
	//	&models.StockInfoHK{},
	//	&models.StockInfoUS{},
	//	&data.FollowedFund{},
	//	&data.FundBasic{},
	//	&models.PromptTemplate{},
	//	&data.Group{},
	//	&data.GroupStock{},
	//	&models.Tags{},
	//	&models.Telegraph{},
	//	&models.TelegraphTags{},
	//	&models.LongTigerRankData{},
	//	&data.AIConfig{},
	//}
	// 自动迁移数据库
	if err := db.Dao.AutoMigrate(models...); err != nil {
		log.Fatalf("数据库迁移失败: %v", err)
	}
	updateMultipleModel()
}

func updateMultipleModel() {
	oldSettings := &models.OldSettings{}
	db.Dao.Model(oldSettings).First(oldSettings)
	aiConfig := &data.AIConfig{}
	db.Dao.Model(aiConfig).First(aiConfig)
	if oldSettings.OpenAiEnable && oldSettings.OpenAiApiKey != "" && aiConfig.ID == 0 {
		aiConfig.Name = oldSettings.OpenAiModelName
		aiConfig.ApiKey = oldSettings.OpenAiApiKey
		aiConfig.BaseUrl = oldSettings.OpenAiBaseUrl
		aiConfig.ModelName = oldSettings.OpenAiModelName
		aiConfig.Temperature = oldSettings.OpenAiTemperature
		aiConfig.MaxTokens = oldSettings.OpenAiMaxTokens
		aiConfig.TimeOut = oldSettings.OpenAiApiTimeOut
		err := db.Dao.Model(aiConfig).Create(aiConfig).Error
		if err != nil {
			logger.SugaredLogger.Error(err.Error())
		}
	}
}
